package com.example.mingyue.service.impl;

import cn.hutool.json.JSONUtil;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mingyue.mapper.PictureMapper;
import com.example.mingyue.mapper.PostMapper;
import com.example.mingyue.model.entity.Picture;
import com.example.mingyue.model.entity.Post;
import com.example.mingyue.service.PictureService;
import jakarta.annotation.Resource;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService {

    /**
     * 搜索图片列表
     * @param searchText
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public IPage<Picture> searchPicture(String searchText, Integer page, Integer pageSize) {

        //起始索引
        Integer startIndex = (page - 1) * pageSize;

        String url = String.format("https://cn.bing.com/images/search?q=%s&first=%s",searchText,page);
        Document doc = null;
        try {
            doc = Jsoup.connect(url).get();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Elements element = doc.select(".iuscp.isv");

        List<Picture> pictureList = new ArrayList<>();
        for (Element element1 : element) {
            String urlImage = element1.select(".iusc").get(0).attr("m");
            Map<String,Object> urlMap = JSONUtil.toBean(urlImage, Map.class);
            String urlImg = (String)urlMap.get("murl");

            String title = element1.select(".inflnk").get(0).attr("aria-label");

            Picture picture = new Picture();
            picture.setUrlImage(urlImg);
            picture.setTitle(title);
            pictureList.add(picture);

            if(pictureList.size()>=pageSize){
                break;
            }
        }

        IPage<Picture> pagePic = new Page<>(page, pageSize);
        pagePic.setRecords(pictureList);

        System.out.println(pagePic);

        return pagePic;
    }
}
